import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:logger/logger.dart';
import 'package:share_plus/share_plus.dart';
import 'package:uuid/uuid.dart';
import 'package:vdrag_saas/Utils.dart';
import 'package:vdrag_saas/api.dart';
import 'package:vdrag_saas/config.dart';
import 'package:vdrag_saas/detail/detail_header.dart';
import 'package:vdrag_saas/detail/http.dart';
import 'package:vdrag_saas/detail/httpUserAction.dart';
import 'package:vdrag_saas/detail/like_icon.dart';
import 'package:vdrag_saas/detail/media_list.dart';
import 'package:vdrag_saas/detail/use_product.dart';
import 'package:vdrag_saas/model/product.dart';

class Detail extends StatefulWidget {
  Function()? onBack;
  int id;
  Detail({required this.onBack, super.key, required this.id});

  @override
  State<Detail> createState() => _Detail();
}

class _Detail extends State<Detail> {
  late int id;
  Product product = Product();
  late Future<Product> _requestProduct;
  Product useProduct = Product();
  final _fontFamily = '思源黑体';
  final logger = Logger();
  bool isMobile = false;
  double _fontSize = 16;
  MainAxisAlignment contextTitleAlign = MainAxisAlignment.start;
  final GlobalKey _anchorKey = GlobalKey();
  final List<LikeIcon> _items = [];
  late Offset _likeButtonPosition;
  String? homeLink = '';

  /// 防止重复计算浏览数
  bool hasAddViewCount = false;

  String textIndent(String txt) {
    return ' ' * 8 + txt;
  }

  void star() {
    product.likeCount++;
    Api.updateLikeCount(product.id!, product.likeCount);
    RenderBox renderBox =
        _anchorKey.currentContext?.findRenderObject() as RenderBox;
    Offset temp = renderBox.localToGlobal(Offset.zero);
    _likeButtonPosition =
        Offset(temp.dx + renderBox.size.width / 2, temp.dy - 56);
    setState(() {
      _items.add(LikeIcon(
        key: Key(const Uuid().v4()),
        offset: _likeButtonPosition,
        onComplete: (LikeIcon icon) {
          setState(() {
            _items.remove(icon);
          });
        },
      ));
    });
  }

  @override
  void initState() {
    if (isMobile) {
      contextTitleAlign = MainAxisAlignment.center;
      _fontSize = 12;
    } else {
      contextTitleAlign = MainAxisAlignment.start;
      _fontSize = 16;
    }
    _requestProduct = requestData();
    Http().get("/api/products/${widget.id}?populate=*").then((data) {
      setState(() {
        useProduct = Product.fromJson(data);
      });
    });
    // 获取用户ip
    HttpUserAction.getIP().then((ip) {
      // print('1111   ' + ip);
      // print('1111   ' + product.name);
      // print('1111   ' + product.id.toString());

      HttpUserAction.recordUserAction(product.id.toString(), ip, product.name);
    });

    super.initState();
  }

  Future<Product> requestData() async {
    int id = widget.id;
    final data = await Http().get("/api/products/$id?populate=*");
    product = Product.fromJson(data);
    product.id = id;
    if (hasAddViewCount == false) {
      product.viewCount++;
      Api.updateViewCount(id, product.viewCount);
      hasAddViewCount = true;
    }
    return product;
  }

  String buildShareContent(int id, String name) {
    return '$name。获取地址${HttpConfig.home}/#/product/detail/$id 来自@星图金能应用商城';
  }

  AppBar buildAppBar(BuildContext context, Function? onBack) {
    bool isMobile = Utils.isMobile(context);
    double screenWidth = MediaQuery.of(context).size.width;
    if (isMobile) {
      return AppBar(
        leading: onBack == null
            ? null
            : IconButton(
                icon: const Icon(Icons.arrow_back),
                onPressed: () {
                  onBack();
                  Navigator.pop(context);
                },
              ),
        actions: [
          Visibility(
            visible: onBack != null,
            child: FutureBuilder(
                initialData: product,
                future: _requestProduct,
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.hasError) {
                    return const Text('数据请求失败');
                  }
                  Product product = snapshot.data;
                  return IconButton(
                      onPressed: () {
                        if (product.id == null) {
                          return;
                        }
                        Share.share(
                            buildShareContent(product.id!, product.name));
                      },
                      icon: const Icon(
                        Icons.share,
                        color: Color(0xff222222),
                      ));
                }),
          )
        ],
        title: const Text("产品详情", style: TextStyle(color: Color(0xff3D3D3D))),
      );
    }
    return AppBar(
      toolbarHeight: 20 + 37 + 54,
      automaticallyImplyLeading: false,
      titleSpacing: 0,
      scrolledUnderElevation: 0.0,
      backgroundColor: const Color(0xfff1f1f1),
      title: SizedBox(
        height: 20 + 37 + 54,
        width: screenWidth,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              alignment: AlignmentDirectional.topStart,
              width: screenWidth,
              color: const Color(0xffffffff),
              padding: EdgeInsetsDirectional.zero,
              child: Container(
                padding: const EdgeInsetsDirectional.symmetric(
                    vertical: 5, horizontal: 15),
                child: Image.asset(
                  'assets/images/logo.png',
                  width: 125,
                  height: 45,
                ),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            Row(
              children: [
                const SizedBox(
                  width: 40,
                ),
                Visibility(
                  visible: onBack != null,
                  child: IconButton(
                    icon: const Icon(
                      Icons.arrow_back,
                      size: 16,
                    ),
                    onPressed: () {
                      if (onBack != null) {
                        onBack();
                      }
                      Navigator.pop(context);
                    },
                  ),
                ),
                const SizedBox(
                  width: 6,
                ),
                const Text("产品详情",
                    style: TextStyle(
                      color: Color(0xff3D3D3D),
                      fontSize: 20,
                    ))
              ],
            )
          ],
        ),
      ),
    );
  }

  // Detail({super.key});
  @override
  Widget build(BuildContext context) {
    isMobile = Utils.isMobile(context);
    double width = isMobile ? 361 : 1300;
    final markdownStyle = MarkdownStyleSheet(
      p: TextStyle(
          fontFamily: _fontFamily,
          height: 2,
          fontSize: isMobile ? 12 : 16,
          color: const Color(0xff333333)),
      h1: TextStyle(
          fontFamily: _fontFamily,
          fontSize: isMobile ? 30 : 36,
          color: const Color(0xff333333)),
      h2: TextStyle(fontFamily: _fontFamily, fontSize: isMobile ? 24 : 30),
      h3: TextStyle(fontFamily: _fontFamily, fontSize: isMobile ? 18 : 24),
      h4: TextStyle(fontFamily: _fontFamily, fontSize: isMobile ? 16 : 22),
      h5: TextStyle(fontFamily: _fontFamily, fontSize: isMobile ? 14 : 16),
      h6: TextStyle(fontFamily: _fontFamily, fontSize: isMobile ? 12 : 14),
    );
    Widget Function(Uri url, String? title, String? alt)? imageBuilder;
    if (isMobile) {
      imageBuilder = (Uri url, String? title, String? alt) {
        return Image.network(
          url.toString(),
          loadingBuilder: (BuildContext context, Widget child,
              ImageChunkEvent? loadingProgress) {
            if (loadingProgress == null) {
              return child;
            }
            return Center(
              child: Image.asset('assets/images/loading.gif', fit: BoxFit.fill),
            );
          },
          errorBuilder:
              (BuildContext context, Object exception, StackTrace? stackTrace) {
            return const Icon(Icons.error);
          },
        );
      };
    }
    return Scaffold(
      appBar: buildAppBar(context, widget.onBack),
      body: Stack(children: [
        SingleChildScrollView(
          child: Center(
            child: Container(
              color: const Color(0xfff1f1f1),
              padding: const EdgeInsetsDirectional.only(
                  start: 18, end: 18, top: 15, bottom: 60),
              child: Container(
                constraints: BoxConstraints(maxWidth: width),
                child: FutureBuilder(
                    initialData: Product(),
                    future: _requestProduct,
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      if (snapshot.hasError) {
                        return const Text('数据请求失败');
                      }
                      Product product = snapshot.data;
                      // homeLink = product.homeLink;
                      return Stack(children: [
                        Column(
                          children: <Widget>[
                            DetailHeader(product: product),
                            MediaList(
                              pictures: product.images,
                              videos: product.vidoes,
                            ),
                            // SingleChildScrollView(
                            //   scrollDirection: Axis.horizontal,
                            //   child: Container(
                            //     height: 300,
                            //     child: Row(
                            //       children: [
                            //         GvVideoPlayer('/uploads/v_Drag_b697a109d1.mp4', autoPlay: true),
                            //         GvVideoPlayer('/uploads/20230907_346a45dccd.mp4', autoPlay: true),
                            //                                 GvVideoPlayer('/uploads/v_Drag_b697a109d1.mp4', autoPlay: true),],),
                            //   ),
                            // ),
                            const Padding(
                                padding: EdgeInsetsDirectional.only(top: 25)),
                            const Padding(
                                padding: EdgeInsetsDirectional.symmetric(
                                    vertical: 5)),
                            MarkdownBody(
                              selectable: true,
                              styleSheet: markdownStyle,
                              data: product.description,
                              imageBuilder: imageBuilder,
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                const Padding(
                                    padding: EdgeInsetsDirectional.symmetric(
                                        vertical: 10)),
                                IconButton(
                                    key: _anchorKey,
                                    onPressed: () {
                                      star();
                                    },
                                    icon: const Icon(Icons.thumb_up_alt,
                                        color: Colors.grey)),
                                const Padding(
                                    padding: EdgeInsetsDirectional.symmetric(
                                        vertical: 4)),
                                Text('点个赞吧',
                                    style: TextStyle(
                                      color: const Color(0xff666666),
                                      fontFamily: _fontFamily,
                                      fontSize: 12,
                                    )),
                                const Padding(
                                    padding: EdgeInsetsDirectional.symmetric(
                                        vertical: 4))
                              ],
                            ),
                          ],
                        )
                      ]);
                    }),
              ),
            ),
          ),
        ),
        Stack(
          children: _items,
        )
      ]),
      floatingActionButton: Visibility(
        visible: isMobile,
        child: Container(
          padding: const EdgeInsetsDirectional.symmetric(horizontal: 10),
          child: Row(
            children: [
              Expanded(
                child: UseProduct(useProduct),
              ),
            ],
          ),
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }
}
